<template>
  <div>
    <div class="root">
      <div class="one">
        <div class="nav">
          <span class="basic">询价清单以及要求</span>
        </div>
        <div class="content">
          <el-form
            :model="detailed"
            style="max-width: 1200px; margin-top: 20px"
            label-width="150px"
          >
            <el-row>
              <el-col :span="12">
                <el-form-item label="询价日期:">
                  <el-date-picker
                    v-model="detailed.inquiryTime"
                    format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD"
                    type="date"
                    placeholder="下拉选择日期"
                    style="width: 300px"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="货物种类:">
                  <el-input
                    v-model="detailed.goodsType"
                    autocomplete="off"
                    placeholder="单行输入"
                    style="width: 300px"
                  />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="12">
                <el-form-item label="运输方式:">
                  <el-select
                    v-model="detailed.shippingid"
                    placeholder="海运/铁路/公路/空运/多联式/散货"
                    style="width: 300px"
                  >
                    <el-option
                      v-for="item in shippings"
                      :key="item.id"
                      :label="item.shipping"
                      :value="item.id"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="航线选择:">
                  <el-select
                    v-model="detailed.routeid"
                    placeholder="请选择"
                    style="width: 300px"
                  >
                    <el-option
                      v-for="item in routes"
                      :key="item.id"
                      :label="item.route"
                      :value="item.id"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="12">
                <el-form-item label="起运港:">
                  <el-input
                    v-model="detailed.startPort"
                    autocomplete="off"
                    placeholder="默认上海"
                    style="width: 300px"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="目的港:">
                  <el-input
                    v-model="detailed.oPort"
                    autocomplete="off"
                    placeholder="请输入"
                    style="width: 300px"
                  />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="12">
                <el-form-item label="报价条款:">
                  <el-select
                    v-model="detailed.clauseid"
                    placeholder="CFR/CIF/DDU/DAP/DDP/其他"
                    style="width: 300px"
                  >
                    <el-option
                      v-for="item in options"
                      :key="item.id"
                      :label="item.clause"
                      :value="item.id"
                    />
                  </el-select>
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="货物描述:">
                  <el-input
                    v-model="detailed.describe"
                    autocomplete="off"
                    placeholder="请输入"
                    style="width: 300px"
                  />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="12">
                <el-form-item label="HS编码:">
                  <el-input
                    v-model="detailed.hscode"
                    autocomplete="off"
                    placeholder="默认 84749000"
                    style="width: 300px"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="柜型选择:">
                  <el-select
                    v-model="detailed.cabinetid"
                    placeholder="拼箱/20GP/40GP/20HQ/40HQ/20FR/40FR"
                    style="width: 300px"
                  >
                    <el-option
                      v-for="item in cabinets"
                      :key="item.id"
                      :label="item.cabinet"
                      :value="item.id"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </div>
      <div class="two">
        <div class="nav">
          <span class="basic">产品信息</span>
        </div>
        <div class="content">
          <!-- 表格数据 -->
          <el-table :data="tableData" stripe style="width: 100%">
            <el-table-column prop="code" label="产品编号" align="center" />
            <el-table-column prop="name" label="产品名称" align="center" />
            <el-table-column prop="num" label="总件数" align="center" />
            <el-table-column
              prop="weight"
              label="总毛重（kg）"
              align="center"
            />
            <el-table-column
              prop="volume"
              label="总体积（CBM）"
              align="center"
            />
            <el-table-column prop="tornu" label="总托数" align="center" />
          </el-table>
          <div class="sp">
            <span>总件数：{{ totalCounts }}</span>
            <span>总毛重（kg）：{{ totalGross }}</span>
            <span>总体积（CBM）：{{ totalVolume }}</span>
            <span>总托数：{{ totalPallets }}</span>
          </div>
        </div>
      </div>
      <div class="three">
        <div class="nav">
          <span class="basic">报价</span>
        </div>
        <el-form
          :model="form"
          style="max-width: 1000px; margin-top: 20px"
          label-width="150px"
        >
          <el-row>
            <el-col :span="12">
              <el-form-item label="报价条款:">
                <el-select
                  v-model="form.clauseid"
                  placeholder="CFR/CIF/DDU/DAP/DDP/其他"
                  style="width: 300px"
                >
                  <el-option
                    v-for="item in options"
                    :key="item.id"
                    :label="item.clause"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="RMB费用:">
                <el-input
                  v-model="form.fee"
                  autocomplete="off"
                  placeholder="单行输入"
                  style="width: 300px"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12">
              <el-form-item label="海运费USD:">
                <el-input
                  v-model="form.seefeeusd"
                  autocomplete="off"
                  placeholder="请输入"
                  style="width: 300px"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="目的港费用合计:">
                <el-input
                  v-model="form.objectfee"
                  autocomplete="off"
                  placeholder="单行输入"
                  style="width: 300px"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12">
              <el-form-item label="报价有效期:">
                <el-date-picker
                  v-model="form.vidtime"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                  type="date"
                  placeholder="请选择"
                  style="width: 300px"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="海运费合计:">
                <el-input
                  v-model="form.seefeetotal"
                  autocomplete="off"
                  placeholder="请输入"
                  style="width: 300px"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12">
              <el-form-item label="船公司:">
                <el-input
                  v-model="form.company"
                  autocomplete="off"
                  placeholder="单行输入"
                  style="width: 300px"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="航次:">
                <el-input
                  v-model="form.voyage"
                  autocomplete="off"
                  placeholder="单行输入"
                  style="width: 300px"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12">
              <el-form-item label="航程:">
                <el-input
                  v-model="form.voyagen"
                  autocomplete="off"
                  placeholder="单行输入"
                  style="width: 300px"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="上传截图:">
                <el-upload
                  class="avatar-uploader"
                  :action="host + '/upload/img'"
                  :show-file-list="false"
                  :before-upload="beforeAvatarUpload"
                  :on-success="handleAvatarSuccess"
                >
                  <img v-if="imageUrl" :src="imageUrl" class="avatar" />
                  <el-icon v-else class="avatar-uploader-icon"
                    ><Plus
                  /></el-icon>
                </el-upload>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>

      <div class="dialog-footer">
        <el-button>关闭</el-button>
        <el-button type="primary" @click="aaa"> 提交 </el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onBeforeMount } from "vue";
import { ElMessage } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import host from "@/utils/env.js";
import { getUser } from "@/utils/session.js";
import { useRoute, useRouter } from "vue-router";
import {
  updateQuote,
  addQuote,
  getQuote,
  updateStatus,
  getProduct,
  getInquiry
} from "@/api/forworder/forworder.js";
import {
  getClause,
  getShipping,
  getRoute,
  getCabinet
} from "@/api/forworder/clause.js";
const user = getUser();
let options = ref([]);
let shippings = ref([]);
let routes = ref([]);
let cabinets = ref([]);
const tableData = ref([]);
const totalCounts = ref(0);
const totalGross = ref(0);
const totalVolume = ref(0);
const totalPallets = ref(0);
const route = useRoute();
const router = useRouter(); // 使用useRouter来获取router实例
const enquiryCode = route.query.enquiryCode; // 获取传递的询价编号
const ordercode = route.query.ordercode; // 获取传递的订单编号
const pan = route.query.mode; //判断是修改还是添加
const imageUrl = ref("");
/**
 * 报价数据
 */
const form = ref({
  fee: "",
  seefeeusd: "",
  objectfee: "",
  vidtime: "",
  seefeetotal: "",
  company: "",
  voyage: "",
  voyagen: "",
  screenshot: "",
  clauseid: "",
  enquiryCode: "",
  fid: "",
  userid: ""
});
const detailed = ref({
  inquiryTime: "",
  goodsType: "",
  shippingid: "",
  routeid: "",
  startPort: "",
  oPort: "",
  clauseid: "",
  describe: "",
  hscode: "",
  cabinetid: "",
  status: "",
  enquiryCode: "",
  userid: ""
});
/**
 * 上传成功
 * @param response
 * @param uploadFile
 */
const handleAvatarSuccess = (response, uploadFile) => {
  if (response.code == 200) {
    //上传成功
    imageUrl.value = URL.createObjectURL(uploadFile.raw);
    form.value.screenshot = response.data;
  }
};

/**
 * 文件上传前的限制
 * @param rawFile
 */
const beforeAvatarUpload = rawFile => {
  console.log(form.value.screenshot);
  if (rawFile.type !== "image/jpeg" && rawFile.type !== "image/png") {
    ElMessage.error("请上传jpg、png格式的文件");
    return false;
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error("图片不能超过2MB!");
    return false;
  }
  return true;
};
/**
 * 判断是添加还是修改报价
 */
if (pan == "add") {
  form.value = {
    fee: "",
    seefeeusd: "",
    objectfee: "",
    vidtime: "",
    seefeetotal: "",
    company: "",
    voyage: "",
    voyagen: "",
    screenshot: "",
    clauseid: "",
    enquiryCode: enquiryCode
  };
} else if (pan == "update") {
  getList();
}
/**
 * 点击事件，完成修改或添加后跳转页面
 */
async function aaa() {
  if (pan == "add") {
    let res = await save();
    if (res == 200) {
      goToIndex();
    }
  } else {
    let re = await update();
    if (re == 200) {
      goToIndex();
    }
  }
}
/**
 * 添加报价
 */
async function save() {
  form.value.enquiryCode = enquiryCode;
  form.value.userid = user.id;
  let res = await addQuote(form.value);
  if (res.code == 200) {
    ElMessage({
      message: "保存成功",
      type: "success"
    });
    detailed.value.enquiryCode = enquiryCode;
    detailed.value.status = 2;
    updateZhuang();
  } else {
    ElMessage({
      message: "保存失败",
      type: "error"
    });
  }
  return res.code;
}
/**
 * 修改报价
 */
async function update() {
  form.value.enquiryCode = enquiryCode;
  form.value.userid = user.id;
  let res = await updateQuote(form.value);
  if (res.code == 200) {
    ElMessage({
      message: "修改成功",
      type: "success"
    });
    detailed.value.enquiryCode = enquiryCode;
    detailed.value.status = 4;
    updateZhuang();
  } else {
    ElMessage({
      message: "修改失败",
      type: "error"
    });
  }
  return res.code;
}
async function updateZhuang() {
  let res = await updateStatus(detailed.value);
}
/**
 * 修改报价时获取报价数据
 */
async function getList() {
  let res = await getQuote(enquiryCode);
  form.value = res.data;
}
// 点击查看报价按钮时跳转
function goToIndex() {
  router.push({
    path: "/forwarder/index" // 跳转的目标页面路径
  });
}
/**
 * 获取产品信息
 */
async function getProductList() {
  let res = await getProduct(ordercode);
  tableData.value = res.data;

  // 计算总和
  totalCounts.value = tableData.value.reduce((sum, item) => sum + item.num, 0);
  totalGross.value = tableData.value.reduce(
    (sum, item) => sum + item.weight,
    0
  );
  totalVolume.value = tableData.value.reduce(
    (sum, item) => sum + item.volume,
    0
  );
  totalPallets.value = tableData.value.reduce(
    (sum, item) => sum + item.tornu,
    0
  );
}
/**
 * 获取询价清单及要求
 */
async function getInqui() {
  let res = await getInquiry(ordercode);
  detailed.value = res.data;
}
/**
 * 获取报价条款
 */
async function getClauseList() {
  let res = await getClause();
  if (res.code === 200) {
    options.value = res.data; // 直接赋值为 res.data
  } else {
    console.error("获取数据失败:", res.msg);
  }
}
/**
 * 获取运输方式
 */
async function getShippingList() {
  let res = await getShipping();
  if (res.code === 200) {
    shippings.value = res.data; // 直接赋值为 res.data
  } else {
    console.error("获取数据失败:", res.msg);
  }
}
/**
 * 获取航线
 */
async function getRouteList() {
  let res = await getRoute();
  if (res.code === 200) {
    routes.value = res.data; // 直接赋值为 res.data
  } else {
    console.error("获取数据失败:", res.msg);
  }
}
/**
 * 获取柜型
 */
async function getCabinetList() {
  let res = await getCabinet();
  if (res.code === 200) {
    cabinets.value = res.data; // 直接赋值为 res.data
  } else {
    console.error("获取数据失败:", res.msg);
  }
}
// 初始化加载列表
onBeforeMount(() => {
  getProductList();
  getClauseList();
  getShippingList();
  getRouteList();
  getCabinetList();
  getInqui();
});
</script>

<style scoped>
.root {
  width: 85vw;
  border-radius: 5px;
}
.nav {
  background-color: #efefef;
  height: 50px;
  line-height: 50px;
  border-bottom: 1px solid #c1c1c1;
}
.basic {
  margin-left: 30px;
}

:deep(.avatar-uploader .avatar) {
  width: 128px;
  height: 128px;
  display: block;
}

:deep(.avatar-uploader .el-upload) {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

:deep(.avatar-uploader .el-upload:hover) {
  border-color: var(--el-color-primary);
}

:deep(.el-icon.avatar-uploader-icon) {
  font-size: 28px;
  color: #8c939d;
  width: 128px;
  height: 128px;
  text-align: center;
}
.dialog-footer {
  width: 150px;
  display: flex;
  justify-content: space-between;
  position: relative;
  left: 40%;
  transform: translateX(-40%);
}
.one,
.two,
.three {
  background-color: #ffffff;
  border: 1px solid #c1c1c1;
}
.two,
.three {
  margin-top: 30px;
}
.sp {
  padding-top: 10px;
  padding-bottom: 10px;
}
.sp span {
  padding: 10px;
}
</style>
